/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package be.free.ts.support;

import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.converters.Converter;
import org.eclipse.persistence.sessions.Session;
import org.joda.time.LocalDate;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Christophe De Blende
 * @since 08/12/12
 */
public class LocalDateConverter implements Converter {

	public Object convertDataValueToObjectValue(Object dataValue, Session session) {
		if (dataValue == null) {
			return null;
		}
		if (dataValue instanceof Date) {
			return new LocalDate(dataValue);
		}
		throw new IllegalStateException("Conversion exception, value is not of java.util.Date type.");
	}

	public Object convertObjectValueToDataValue(Object objectValue, Session session) {
		if (objectValue == null) {
			return null;
		}

		if (objectValue instanceof LocalDate) {
			LocalDate localDate = (LocalDate) objectValue;
			String dateString = localDate.toString();
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			try {
				return df.parse(dateString);
			} catch (ParseException e) {
				throw new IllegalStateException("Unable to parse the date format.", e);
			}

		}
		throw new IllegalStateException("Conversion exception, value is not of LocalDate type.");
	}

	public void initialize(DatabaseMapping dm, Session session) {
		dm.getField().setType(java.sql.Date.class);
	}

	public boolean isMutable() {
		return false;
	}

}